package com.ouman.luoliluoli.mainfragments;

import android.content.Context;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.ouman.luoliluoli.MainActivity;
import com.ouman.luoliluoli.R;
import com.ouman.luoliluoli.adapters.LuoliTalkRecyclerViewAdapter;
import com.ouman.luoliluoli.models.LuoliTalkModel;
import com.ouman.luoliluoli.utils.GlobalConstants;
import com.ouman.luoliluoli.utils.NetworkHelper;

import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import static android.widget.Toast.LENGTH_SHORT;


public class LuoliTalkFragment extends Fragment {

    private OnFragmentInteractionListener mListener;
    private NetworkHelper networkHelper;

    private RecyclerView recyclerView;
    private LuoliTalkRecyclerViewAdapter adapter;
    private List<LuoliTalkModel> luoliTalkModelList;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String LAST_UPDATE = "201409";
    private Button buttonLoadMore;

    private Boolean isUpdate = false;
    private int loadPage = 2;

    public LuoliTalkFragment() {
        // Required empty public constructor
    }


    public static LuoliTalkFragment newInstance(String param1, String param2) {
        LuoliTalkFragment fragment = new LuoliTalkFragment();
        Bundle args = new Bundle();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ((MainActivity) getActivity()).setAppBarElevation(0);
        View rootView = inflater.inflate(R.layout.fragment_luoli_talk, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerViewTalk);
        buttonLoadMore = (Button) rootView.findViewById(R.id.buttonLoadMore);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        networkHelper = new NetworkHelper();

        luoliTalkModelList = new ArrayList<>();
        //add swipe refresh on recycler view
        swipeRefreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.swipeLuoliTalk);
        swipeRefreshLayout.setSize(SwipeRefreshLayout.DEFAULT);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.black, android.R.color.holo_red_light,
                android.R.color.holo_green_dark, android.R.color.holo_orange_dark);
        swipeRefreshLayout.setProgressViewEndTarget(true, 200);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // check network

                if (networkHelper.isConnect(getActivity())){
                    new  Thread(getHttpThread).start();
                }else {
                    Toast.makeText(getActivity(), "貌似没有网络连接啊", Toast.LENGTH_SHORT).show();
                }
                swipeRefreshLayout.setRefreshing(false);
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.recyclerview_spacing);
        recyclerView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));

        adapter = new LuoliTalkRecyclerViewAdapter(getActivity(), luoliTalkModelList);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int y;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == recyclerView.SCROLL_STATE_IDLE && y>0){
                    ((MainActivity) getActivity()).hideFloatingActionButton();
                }else if(newState == recyclerView.SCROLL_STATE_IDLE && y<0){
                    ((MainActivity) getActivity()).setAppBarElevation(0);
                    ((MainActivity) getActivity()).showFloatingActionButton();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                y = dy;
                //上滑隐藏fab
                if (dy > 0)
                {
                    ((MainActivity) getActivity()).hideFloatingActionButton();
                }else{
                    ((MainActivity) getActivity()).setAppBarElevation(0);
                    ((MainActivity) getActivity()).showFloatingActionButton();
                }
            }
        });



        if (networkHelper.isConnect(getContext())){
            System.out.println("开始请求news了嘛？？？？");
            new  Thread(getHttpThread).start();
        }else {
            Toast.makeText(getActivity(), "no connection, please check your network.", Toast.LENGTH_SHORT).show();
        }

        buttonLoadMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadPage += 1;
                new Thread(getLoadMoreThread).start();
            }
        });
    }


    public class SpaceItemDecoration extends RecyclerView.ItemDecoration{
        private int space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            if(parent.getChildPosition(view) != 0)
                outRect.top = space;
        }
    }

    private  Thread getHttpThread = new Thread(){
        public void run(){
            //In here we solve http request to get data
            HttpURLConnection connection = null;
            try {
                String urlNews = GlobalConstants.API_LUOLI_TALK;
                URL url = new URL(urlNews);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();
                    JSONObject jsonObject = new JSONObject(result);

                    String status = jsonObject.getString("status");
                    if (!isUpdate){
                        if (status.equals("success")){
                            JSONArray jsonArray = jsonObject.getJSONArray("data");
                            for (int i=0; i < jsonArray.length();i++){
                                JSONObject  jsonItem = jsonArray.getJSONObject(i);
                                int news_id = jsonItem.getInt("news_id");
                                String title = jsonItem.getString("news_title");
                                String authorName = jsonItem.getString("news_author_name");
                                String authorSign = jsonItem.getString("news_author_sign");
                                String authorAvatarUrl = jsonItem.getString("news_author_avatar_url");
                                String newsHeadImageUrl = jsonItem.getString("news_head_image_url");
                                String newsContent = jsonItem.getString("news_content");
                                String newsTime = jsonItem.getString("news_post_time");

                                Integer numWatched = jsonItem.getInt("news_num_watched");
                                Integer numLiked = jsonItem.getInt("news_num_liked");

                                LuoliTalkModel luoliTalkModel = new LuoliTalkModel();
                                luoliTalkModel.setNews_id(news_id);
                                luoliTalkModel.setNews_author_avatar_url(authorAvatarUrl);
                                luoliTalkModel.setNews_author_name(authorName);
                                luoliTalkModel.setNews_author_sign(authorSign);
                                luoliTalkModel.setNews_content(newsContent);
                                luoliTalkModel.setNews_head_image_url(newsHeadImageUrl);
                                luoliTalkModel.setNews_title(title);
                                luoliTalkModel.setNews_post_time(newsTime);

                                luoliTalkModel.setNews_num_watched(numWatched);
                                luoliTalkModel.setNews_num_liked(numLiked);
                                luoliTalkModelList.add(luoliTalkModel);
                            }

                            Message msg =  Message.obtain();
                            msg.what = 0;
                            getHttpHandler.sendMessage(msg);

                        } else{
                            Message msg =  Message.obtain();
                            msg.what = 1;
                            getHttpHandler.sendMessage(msg);
                        }
                    } else {
                        Message msg = Message.obtain();
                        msg.what = 2;
                        getHttpHandler.sendMessage(msg);
                    }

                }
            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };

    private  Thread getLoadMoreThread = new Thread(){
        public void run(){
            //In here we solve http request to get data
            HttpURLConnection connection = null;
            try {
                String urlNews = GlobalConstants.API_LUOLI_TALK + "?page=" + loadPage;
                URL url = new URL(urlNews);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                if (connection.getResponseCode() == 200){
                    InputStream is = connection.getInputStream();
                    String result = IOUtils.toString(is);
                    System.out.println(result);
                    is.close();
                    JSONObject jsonObject = new JSONObject(result);

                    String status = jsonObject.getString("status");
                    if (status.equals("success")){
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        for (int i=0; i < jsonArray.length();i++){
                            JSONObject  jsonItem = jsonArray.getJSONObject(i);
                            int news_id = jsonItem.getInt("news_id");
                            String title = jsonItem.getString("news_title");
                            String authorName = jsonItem.getString("news_author_name");
                            String authorSign = jsonItem.getString("news_author_sign");
                            String authorAvatarUrl = jsonItem.getString("news_author_avatar_url");
                            String newsHeadImageUrl = jsonItem.getString("news_head_image_url");
                            String newsContent = jsonItem.getString("news_content");
                            String newsTime = jsonItem.getString("news_post_time");

                            Integer numWatched = jsonItem.getInt("news_num_watched");
                            Integer numLiked = jsonItem.getInt("news_num_liked");

                            LuoliTalkModel luoliTalkModel = new LuoliTalkModel();
                            luoliTalkModel.setNews_id(news_id);
                            luoliTalkModel.setNews_author_avatar_url(authorAvatarUrl);
                            luoliTalkModel.setNews_author_name(authorName);
                            luoliTalkModel.setNews_author_sign(authorSign);
                            luoliTalkModel.setNews_content(newsContent);
                            luoliTalkModel.setNews_head_image_url(newsHeadImageUrl);
                            luoliTalkModel.setNews_title(title);
                            luoliTalkModel.setNews_post_time(newsTime);

                            luoliTalkModel.setNews_num_watched(numWatched);
                            luoliTalkModel.setNews_num_liked(numLiked);
                            luoliTalkModelList.add(luoliTalkModel);
                        }

                        Message msg =  Message.obtain();
                        msg.what = 0;
                        getHttpHandler.sendMessage(msg);

                    } else if (status.equals("info")){
                        // no more news
                        Message msg =  Message.obtain();
                        msg.what = 3;
                        getHttpHandler.sendMessage(msg);
                    }

                }
            } catch (IOException e){
                e.printStackTrace();
            } catch (JSONException e){
                e.printStackTrace();
            } finally{
                if (connection != null){
                    connection.disconnect();
                }
            }

        }
    };

    private Handler getHttpHandler = new Handler(){
        public void handleMessage(Message msg){
            if (msg.what == 0){
                //add data stop refresher and send to adapter data
                //changed
                adapter.notifyDataSetChanged();
                isUpdate = true;
                swipeRefreshLayout.setRefreshing(false);
            }else if (msg.what == 1){
                Toast.makeText(getActivity(), "糟糕，服务器出现了致命的错误", LENGTH_SHORT).show();
            }else if (msg.what == 2){
                Toast.makeText(getActivity(), "已更新至最新", LENGTH_SHORT).show();
                swipeRefreshLayout.setRefreshing(false);
            }else if (msg.what == 3){
                Toast.makeText(getActivity(), "没有更多了", LENGTH_SHORT).show();
            }
        }
    };




    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
